package com.lfs.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.lfs.admin.dao.AgtWalletInfoDao;
import com.lfs.admin.dao.WalletDailySummaryDao;
import com.lfs.admin.dao.WalletDetailDao;
import com.lfs.admin.model.entity.AgtWalletDailySummaryEntity;
import com.lfs.admin.model.entity.AgtWalletDetailEntity;
import com.lfs.admin.model.entity.AgtWalletInfoEntity;
import com.lfs.admin.model.vo.AgentInfoVO;
import com.lfs.admin.model.vo.AgtWalletDetailSummaryVO;
import com.lfs.admin.model.vo.AgtWalletDetailVO;
import com.lfs.admin.model.vo.AgtWalletInfoVO;
import com.lfs.admin.service.AgtWalletInfoService;
import com.lfs.admin.service.system.TokenService;
import com.lfs.common.core.domain.entity.SysUser;
import com.lfs.common.core.domain.model.LoginUser;
import com.lfs.common.utils.ServletUtils;
import com.lfs.common.utils.StringUtils;
import com.lfs.dao.entity.PageBean;
import com.github.pagehelper.PageHelper;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class AgtWalletInfoServiceImpl implements AgtWalletInfoService {

    @Autowired
    private AgtWalletInfoDao agtWalletInfoDao;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WalletDetailDao walletDetailDao;

    @Autowired
    private WalletDailySummaryDao walletDailySummaryDao;

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public PageBean<AgtWalletInfoEntity> queryAgtWallet(AgtWalletInfoVO agtWalletInfoVO) {
        List<AgtWalletInfoEntity> walletApproveList = new ArrayList<>();
        try {
            PageHelper.startPage(agtWalletInfoVO.getCurrentPage(), agtWalletInfoVO.getPageSize());
            walletApproveList = agtWalletInfoDao.queryAgtWallet(agtWalletInfoVO);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageBean<AgtWalletInfoEntity>(walletApproveList);
    }

    @Override
    public AgtWalletInfoEntity getAgtWallet() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String agtPhone = StringUtils.isBlank(user.getUserName()) ? "error" : user.getUserName();
        return agtWalletInfoDao.getAgtWallet(agtPhone);
    }

    @Override
    public PageBean<AgtWalletDetailEntity> queryWalletDetail(AgtWalletDetailVO agtWalletDetailVO) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String agtPhone = StringUtils.isBlank(user.getUserName()) ? "error" : user.getUserName();
        agtWalletDetailVO.setAgtPhone(agtPhone);
        List<AgtWalletDetailEntity> walletDetailEntityList = new ArrayList<>();
        try {
            PageHelper.startPage(agtWalletDetailVO.getCurrentPage(), agtWalletDetailVO.getPageSize());
            walletDetailEntityList = walletDetailDao.selectDetails(agtWalletDetailVO);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageBean<AgtWalletDetailEntity>(walletDetailEntityList);
    }

    @Override
    public PageBean<AgtWalletDailySummaryEntity> queryWalletDetailSummary(AgtWalletDetailSummaryVO agtWalletDetailSummaryVO) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        String agtPhone = StringUtils.isBlank(user.getUserName()) ? "error" : user.getUserName();
        agtWalletDetailSummaryVO.setAgtPhone(agtPhone);
        List<AgtWalletDailySummaryEntity> walletDailySummaryEntities = new ArrayList<>();
        try {
            PageHelper.startPage(agtWalletDetailSummaryVO.getCurrentPage(), agtWalletDetailSummaryVO.getPageSize());
            walletDailySummaryEntities = walletDailySummaryDao.selectDailySummaries(agtWalletDetailSummaryVO);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new PageBean<AgtWalletDailySummaryEntity>(walletDailySummaryEntities);
    }

    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional
    public void generateDailySummary() {
        String yesterday = LocalDate.now().minusDays(1).format(DATE_FORMATTER);
        AgtWalletDetailSummaryVO agtWalletDetailSummaryVO = new AgtWalletDetailSummaryVO();
        agtWalletDetailSummaryVO.setRecordDate(yesterday);
        generateDailySummaryForDate(agtWalletDetailSummaryVO);
    }

    @Transactional
    @Override
    public void generateDailySummaryForDate(AgtWalletDetailSummaryVO agtWalletDetailSummaryVO) {
        // 1. 检查是否已统计过
        if (walletDailySummaryDao.existsDailySummary(agtWalletDetailSummaryVO) > 0) {
            return; // 已统计过则跳过
        }

        // 2. 查询所有有交易记录的代理商
        List<String> agentPhones = walletDailySummaryDao.selectAgentsWithTransactions(agtWalletDetailSummaryVO.getRecordDate());
        if (CollectionUtil.isEmpty(agentPhones)) {
            return; // 当天无交易
        }

        // 3. 批量统计各代理商的交易数据
        List<AgtWalletDailySummaryEntity> summaries = walletDailySummaryDao.calculateDailySummary(agtWalletDetailSummaryVO);

        // 4. 保存统计结果
        summaries.forEach(summary -> {
            summary.setRecordDate(agtWalletDetailSummaryVO.getRecordDate());
            walletDailySummaryDao.upsertDailySummary(summary);
        });

    }

    /**
     * 手动触发重新生成某天的统计(用于补数据或修正)
     */
    @Transactional
    @Override
    public void regenerateDailySummary(AgtWalletDetailSummaryVO agtWalletDetailSummaryVO) {
        // 1. 删除原有统计
        walletDailySummaryDao.deleteByDate(agtWalletDetailSummaryVO);

        // 2. 重新生成
        generateDailySummaryForDate(agtWalletDetailSummaryVO);
    }
}
